package cd.tools;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;

import java.util.ArrayList;
import java.util.List;

public class NetworkUtil {
	private static List<NetworkStatusListener> listNetworkStatusListener;
	private static NetworkUtil mNetworkUtil;
	private static Context mContent;
	private boolean flag = false;
	ServiceConnection conn = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			NetworkServer.NetworkBinder binder = (NetworkServer.NetworkBinder) service;
			NetworkServer mNetworkServer = binder.getService();
			mNetworkServer.setNetworkListener(new NetworkServer.NetworkListener(){
				@Override
				public void networkAvailable() {
					for(NetworkStatusListener mNetworkStatusListener:listNetworkStatusListener){
						mNetworkStatusListener.networkAvailable();
					}
				}
				@Override
				public void networkNotAvailable() {
					for(NetworkStatusListener mNetworkStatusListener:listNetworkStatusListener){
						mNetworkStatusListener.networkNotAvailable();
					}
				}				
			});
			mNetworkServer.startCheckNetworkStatus();
			flag = true;
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			flag = false;
		}

	};

	public static NetworkUtil getInstance(Context content){
		if(mNetworkUtil == null){
			mContent = content;
			listNetworkStatusListener = new ArrayList<NetworkStatusListener>();
			mNetworkUtil = new NetworkUtil();		
		}
		return mNetworkUtil;
	}		

	public void startListenNetwork() {
		Intent it = new Intent(mContent, NetworkServer.class);
		mContent.bindService(it, conn, Context.BIND_AUTO_CREATE);
	}

	public void stopListenNetwork() {
		if (flag == true) {
			mContent.unbindService(conn);
			flag = false;
		}
	}

	public void setNetworkStatusListener(NetworkStatusListener mNetworkStatusListener){
		listNetworkStatusListener.add(mNetworkStatusListener);
	}
	public interface NetworkStatusListener{
		public void networkAvailable();
		public void networkNotAvailable();
	}
	
	/**
	 * 检查当前网络是否可用
	 * 
	 * @param context
	 * @return
	 */

	public static boolean isNetworkAvailable(Context context) {

		// 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		if (connectivityManager == null) {
			return false;
		} else {
			// 获取NetworkInfo对象
			NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

			if (networkInfo != null && networkInfo.length > 0) {
				for (int i = 0; i < networkInfo.length; i++) {
					// 判断当前网络状态是否为连接状态
					if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}
}
